package com.tbvtc.agriculturalcreditchainserver2025.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.HexUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Crop;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Test;
import com.tbvtc.agriculturalcreditchainserver2025.entity.User;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.CropMapper;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.LargeDateScreenMapper;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.TestMapper;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.UserMapper;
import com.tbvtc.agriculturalcreditchainserver2025.service.FarmerSerive;
import com.tbvtc.agriculturalcreditchainserver2025.service.LargeDateScreenService;
import com.tbvtc.agriculturalcreditchainserver2025.service.PestService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.BlockBaseUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.BlockchainUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestConstant;
import com.tbvtc.agriculturalcreditchainserver2025.utils.UserType;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Cart.CartSelectPhoneAndGoodByUserId;
import com.tbvtc.agriculturalcreditchainserver2025.vo.LargeDateScreen.CropInfoVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.LargeDateScreen.RevenueAnalysisVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.LargeDateScreen.TestMonthSummary;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Pest.getCropPestReportVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.farmerVo.FoodReportVo;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;

@Service
public class LargeDateScreenServiceImpl implements LargeDateScreenService {
    @Autowired
    private CropMapper cropMapper;
    @Autowired
    private BlockchainUtils blockchainUtils;
    @Autowired
    private BlockBaseUtils blockBaseUtils;
    @Autowired
    private FarmerSerive farmerSerive;
    @Autowired
    private TestMapper testMapper;
    @Autowired
    private LargeDateScreenMapper largeDateScreenMapper;
    @Autowired
    private PestService pestService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List getCropInfo() {
        LambdaQueryWrapper<Crop> queryWrapper = new LambdaQueryWrapper<Crop>()
                .select(Crop::getLandName, Crop::getName);
        List<Crop> list = cropMapper.selectList(queryWrapper);
        List<CropInfoVo> cropInfoVos = BeanUtil.copyToList(list, CropInfoVo.class);
        cropInfoVos.forEach(s->{
            try {
                List<FoodReportVo> report = farmerSerive.getReport(s.getName());
//                List<FoodReportVo> reportVos = BeanUtil.copyToList(report, FoodReportVo.class);
                if (report != null && !report.isEmpty()){
                    FoodReportVo foodReportVo = report.get(report.size() - 1);
                    System.out.println(foodReportVo);
                    if (foodReportVo==null){
                        s.setGrowthStage( "添加农作物报告");
                    }
                    s.setGrowthStage( foodReportVo.getReportType());

                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        return cropInfoVos;
    }

    @Override
    public Map getEvidenceCountAndgetRecentEvidence() {
        BigInteger number;
        try {
            number = blockchainUtils.getBlockNumber(
                    blockBaseUtils.getPemFilePath(UserType.ADMIN)
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        String timestamp = "";
        try {
            timestamp = blockchainUtils.getBlockTimestamp(
                    blockBaseUtils.getPemFilePath(UserType.ADMIN)
            );
        } catch (Exception e) {
        }
        BigInteger integer = HexUtil.toBigInteger(timestamp.substring(2));

        Date date = new Date(integer.longValue());

        // 3. 定义目标格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        // 4. 格式化为字符串
        String formattedDate = sdf.format(date);
        System.out.println(formattedDate); // 输出: 2024-03-20 14:30
        Map map = new HashMap();
        map.put("number", number);
        map.put("timestamp", formattedDate);
        return map;

    }

    @Override
    public RevenueAnalysisVo getRevenueAnalysis(String phoen) {
        List<TestMonthSummary> analysis = largeDateScreenMapper.getRevenueAnalysis();
        HashMap<String, List<TestMonthSummary>> collectByPhone = analysis.stream().collect(Collectors.groupingBy(
                TestMonthSummary::getPhone,
                // 可选：保持插入顺序的LinkedHashMap
                HashMap::new,
                Collectors.toList()
        ));
        List<TestMonthSummary> testMonthSummaries = collectByPhone.get(phoen);

        Map<String, List<TestMonthSummary>> collect = testMonthSummaries.stream().collect(Collectors.groupingBy(TestMonthSummary::getMonth));
        // 根据键排序
        collect = collect.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(new Function<Map.Entry<String, List<TestMonthSummary>>, String>() {
                    @Override
                    public String apply(Map.Entry<String, List<TestMonthSummary>> stringListEntry) {
                        return stringListEntry.getKey();
                    }
                }, new Function<Map.Entry<String, List<TestMonthSummary>>, List<TestMonthSummary>>() {
                    @Override
                    public List<TestMonthSummary> apply(Map.Entry<String, List<TestMonthSummary>> stringListEntry) {
                        return stringListEntry.getValue();
                    }
                }, new BinaryOperator<List<TestMonthSummary>>() {
                    @Override
                    public List<TestMonthSummary> apply(List<TestMonthSummary> testMonthSummaries, List<TestMonthSummary> testMonthSummaries2) {
                        return testMonthSummaries;
                    }
                }, new Supplier<Map<String, List<TestMonthSummary>>>() {
                    @Override
                    public Map<String, List<TestMonthSummary>> get() {
                        return new LinkedHashMap<>();
                    }
                }));

        List<Map<String, Object>> list=new ArrayList<>();
        //总收入计算
        BigDecimal TotalbigDecimal = new BigDecimal(0);
        collect.forEach((date, testMonthSummaries1) -> {
            //每个月的收入
            BigDecimal bigDecimal = new BigDecimal(0);
            for (TestMonthSummary testMonthSummary : testMonthSummaries1) {
                bigDecimal = bigDecimal.add(testMonthSummary.getTotalPrice());

            }
            Map<String, Object> res = new HashMap<>();
            res.put("bigDecimal", bigDecimal);
            res.put("date", date);
            list.add(res);
        });
        //年总收入计算
        for (Map<String, Object> stringObjectMap : list) {
            BigDecimal bigDecimal = (BigDecimal)stringObjectMap.get("bigDecimal");
            TotalbigDecimal = TotalbigDecimal.add(bigDecimal);
        }
        RevenueAnalysisVo revenueAnalysisVo=new RevenueAnalysisVo();
        revenueAnalysisVo.setTotalbigDecimal(TotalbigDecimal);
        revenueAnalysisVo.setRevenueAnalysisMap(list);
        return revenueAnalysisVo;


    }

    @Override
    public List<getCropPestReportVo>  pestInfo(Integer userId) {
        User user = userMapper.selectById(userId);
        LambdaQueryWrapper<Crop> queryWrapper = new LambdaQueryWrapper<Crop>()
                .eq(Crop::getPhone, user.getPhone());
        List<Crop> crops = cropMapper.selectList(queryWrapper);
        List<getCropPestReportVo> pestReportVos = new ArrayList<>();
        crops.forEach(s->{

            List<getCropPestReportVo> pestReportList = pestService.getPestReport(s.getName());
            if (!pestReportList.isEmpty()){
                getCropPestReportVo reportVo = pestReportList.get(pestReportList.size() - 1);
                if (!PestConstant.GetHealthName.equals(reportVo.getPestName())&&s.getIsPest()==1){
                    pestReportVos.add(reportVo);
                    cropMapper.updatePest(s.getId());
                }
            }

        });
        return pestReportVos;
    }

    @Override
    public void cancelPest(String name) {
        cropMapper.cancelPest(name);
    }


}
